package com.bs.rss.user;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.bs.rss.common.enums.EnumPagine;
import com.bs.rss.common.model.data.User;
import com.bs.rss.common.model.data.UserInfo;
import com.bs.rss.common.utils.BASE64encry;
import com.bs.rss.common.utils.JsonReturn;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.render.JsonRender;
import com.jfinal.upload.UploadFile;

/** 
 * @author  作者 E-mail: 
 * @date 创建时间：2017年4月15日 下午8:18:16 
 * @version 1.0 
 * @parameter  
 * @since  
 * @return  
 */
public class UserController extends Controller{
	
	
	public void unlock(){
		
		String p = getPara("password","");
		
		String n = getPara("username","");
		
		User u = User.dao.findbyloginname(n);
		
		Ret ret ;
		
		if (u != null && BASE64encry.encry(p).equals(u.getPassword())) {
			
			ret = Ret.ok("msg", "解锁成功");
			
		}else{
			ret = Ret.fail("msg","用户名或密码错误");
		}
		
		renderJson(ret);
		
	}
	@Clear
	public void login() {
		/**
		 * 登录验证
		 */
		String base =  getRequest().getScheme()+"://"+getRequest().getServerName()+":"+getRequest().getServerPort()+getRequest().getContextPath();
		setSessionAttr("basepath", base);
		
		String loginName = getPara("loginname", "");
		String pass = getPara("password", "");
		Ret ret;
		User u = User.dao.findbyloginname(loginName);

		if (u != null && BASE64encry.encry(pass).equals(u.getPassword())) {

			setSessionAttr("currentuser", u);
			ret = Ret.ok("obj", u);
		
		} else {
			
			ret = Ret.fail("msg", "用户名或密码错误");
		}
		renderJson(ret);
	}
	@Clear
	@Before({ RegValidator.class, Tx.class })
	public void reg() {

		Ret ret = Ret.fail("msg", "注册失败");
		;
		User u = getModel(User.class, "u");
		UserInfo uf = getModel(UserInfo.class, "i");
		User u0 = User.dao.findbyloginname(u.getLoginname());
		if (u0 == null) {
			u.setCtime(new Date());
			u.setRealname(uf.getRealname1());
			u.setPassword(BASE64encry.encry(u.getPassword()));
			boolean flag = u.save();
			
			uf.setCtime(new Date());
			uf.setUserId(u.getId());
			
			boolean flag1 = uf.save();
			if (flag && flag1) {
				ret = Ret.ok("msg", "注册成功");
			}
		} else {
			ret = Ret.fail("msg", "用户名已存在");
		}
		renderJson(ret);
	}
	public void logout() {

		getSession().invalidate();

		redirect("/");
	}
	
	public void upd(){
		

		boolean f = false;
		Ret t = JsonReturn.re.saveFail(EnumPagine.fail);
		UserInfo ui =  getModel(UserInfo.class, "");
		UserInfo ui0 =  UserInfo.dao.findById(ui.getId());
		ui.setUserId(ui0.getUserId());
		ui.setCtime(ui0.getCtime());
		f = ui.update();
		
		if(f){t = JsonReturn.re.saveOk(EnumPagine.ok, f);}
		
		renderJson(t);
		
	}
	
	public void users(){
		renderJson(User.dao.findall(getParaToInt("pageIndex", 1), getParaToInt("pageSize", 10)));
	}
	public void user(){
		
		User u = getSessionAttr("currentuser");
		
		UserInfo ui = UserInfo.dao.findById(u.getId());
				
		renderJson(Ret.ok("userInfo", ui));
		
	}
	/**
	 * 文件上传接口
	 */
	@Clear
	public void upload() {
		Map<String, Object> json = new HashMap<>();
		Map<String, Object> data = new HashMap<>();

		String path = new SimpleDateFormat("yyyy/MM/dd/HH/mm/ss").format(new Date());
		UploadFile file = getFile("file");
		File source = file.getFile();
		String fileName = file.getFileName();

		json.put("filename", fileName);

		String extension = fileName.substring(fileName.lastIndexOf("."));
		String prefix;
		if (".png".equals(extension) || ".jpg".equals(extension) || ".gif".equals(extension)) {
			prefix = "img";
			fileName = generateWord() + extension;
		} else {
			prefix = "file";
		}

		try {
			FileInputStream fis = new FileInputStream(source);
			File targetDir = new File(PathKit.getWebRootPath() + "/" + prefix + "/u/" + path);
			if (!targetDir.exists()) {
				targetDir.mkdirs();
			}
			File target = new File(targetDir, fileName);
			if (!target.exists()) {
				target.createNewFile();
			}
			FileOutputStream fos = new FileOutputStream(target);
			byte[] bts = new byte[300];
			while (fis.read(bts, 0, 300) != -1) {
				fos.write(bts, 0, 300);
			}
			fos.close();
			fis.close();
			json.put("isSuccess", true);
			json.put("code", 0);
			json.put("url", prefix + "/u/" + path + "/" + fileName);
			data.put("src", prefix + "/u/" + path + "/" + fileName);
			json.put("data", data);
			source.delete();

		} catch (FileNotFoundException e) {
			json.put("isSuccess", false);
			json.put("code", 1);
			json.put("msg", "上传出现错误，请稍后再上传");
		} catch (IOException e) {
			json.put("isSuccess", false);
			json.put("code", 1);
			json.put("msg", "文件写入服务器出现错误，请稍后再上传");
		}

		// getResponse().setContentType("application/json;charset=UTF-8");
		// renderJson(json);
		render(new JsonRender(json).forIE());
	}

	/**
	 * 文件下载
	 */
	public void _download() {
		String path = PathKit.getWebRootPath() + "/" + getPara("url");
		renderFile(path);
	}

	// 生成文件名
	private String generateWord() {
		String[] beforeShuffle = new String[] { "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F",
				"G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
		List<String> list = Arrays.asList(beforeShuffle);
		Collections.shuffle(list);
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < list.size(); i++) {
			sb.append(list.get(i));
		}
		String afterShuffle = sb.toString();
		String result = afterShuffle.substring(5, 9);
		return result;
	}

	
	public void dy(){
		
	}
	
}
